package com.intelligentpension.kotlinbluetoothprint.service

import android.annotation.SuppressLint
import android.app.Service
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import com.intelligentpension.kotlinbluetoothprint.printutils.PrintOrderDataMaker
import com.intelligentpension.kotlinbluetoothprint.utils.ConstantUtils
import com.intelligentpension.kotlinbluetoothprint.utils.ThreadUtils
import com.orhanobut.logger.Logger


/**
 * 版权：点赞 版权所有
 * author :赵航
 * @e-mail: zhaohangcn@gmail.com
 * time：2022/4/5
 * describe ：
 */
class BtService : Service() {
    private lateinit var mAdapter: BluetoothAdapter
    private val mQueue: ArrayList<ByteArray> = ArrayList()

    //第一次创建服务时执行的方法，且只执行一次
    override fun onCreate() {
        super.onCreate()
        mAdapter = (getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter
    }

    //客户端通过调用bindService()方法启动服务时执行该方法
    override fun onBind(p0: Intent?): IBinder? = null

    //客户端通过调用startService()方法启动服务时执行该方法，可以执行多次
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        var adress = intent?.getStringExtra(ConstantUtils.ADRESS)
        Logger.e("哈哈哈哈哈哈" + intent?.action + "=========" + adress)
        if (ConstantUtils.TEST_ACTION == intent?.action) {
            var dev = mAdapter.getRemoteDevice(adress)
            pintOne(dev)
        }
        return super.onStartCommand(intent, flags, startId)
    }

    @SuppressLint("MissingPermission")
    private fun pintOne(dev: BluetoothDevice) {

        //设置打印纸张的宽和高
        var pintDataMaker= PrintOrderDataMaker(this,58,255)

        //获取的打印数据
        var printData = pintDataMaker.getPrintData()
        mQueue.clear()
        mQueue.addAll(printData)

        //连接蓝牙创建通道
        var socket = dev.createRfcommSocketToServiceRecord(ConstantUtils.BluetoothUUID)

        ThreadUtils.executeSubThread {

            try {
                //连接蓝牙
                if (!socket.isConnected) {
                    socket.connect()
                }

                //向外输出打印内容
                var outputStream = socket.outputStream

                while(mQueue.size>0){
                    outputStream.write(mQueue[0])
                    mQueue.removeAt(0)
                }

            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

    }


    //客户端调用unBindeService()方法断开服务绑定时执行该方法
    override fun unbindService(conn: ServiceConnection) {
        super.unbindService(conn)
    }

    //服务被销毁时执行的方法，且只执行一次
    override fun onDestroy() {
        super.onDestroy()
    }


}